package com.hjm.strategy.kdb;



import cn.hutool.json.JSONUtil;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author
 */
public class KdbSignUtil {
    public static String parseRequest(HttpServletRequest request){
        String body = "";
        try {
            ServletInputStream inputStream = request.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            while(true){
                String info = br.readLine();
                if(info == null){
                    break;
                }
                if("".equals(body)){
                    body = info;
                }else{
                    body += info;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return body;
    }

    public static String getPlainText(Map<String, Object> map) {
        ArrayList<String> list = new ArrayList<String>();
        for(Map.Entry<String, Object> entry : map.entrySet()){
            if(entry.getValue() != null && !"".equals(entry.getValue()) && !"sign".equalsIgnoreCase(entry.getKey()) && !"file".equalsIgnoreCase(entry.getKey())){
                String value = entry.getValue().toString();
                if(entry.getValue() instanceof List || entry.getValue() instanceof Map){
                    value = JSONUtil.toJsonStr(entry.getValue());
                }
                list.add(entry.getKey() + "=" + value + "&");
            }
        }
        int size = list.size();
        String [] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < size; i ++) {
            sb.append(arrayToSort[i]);
        }
        return sb.substring(0, sb.length()-1);
    }
}
